package com.pai4j.message.core.interceptor;

import com.pai4j.message.model.MessageContext;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 拦截器链
 * 管理和执行消息拦截器链
 *
 * @author PAI4J Team
 * @date 2025-11-01
 */
@Slf4j
public class InterceptorChain {

    /**
     * 拦截器列表（按order排序）
     */
    private final List<MessageInterceptor> interceptors;

    private InterceptorChain(List<MessageInterceptor> interceptors) {
        this.interceptors = interceptors.stream()
                .filter(MessageInterceptor::isEnabled)
                .sorted(Comparator.comparingInt(MessageInterceptor::getOrder))
                .collect(Collectors.toList());
    }

    /**
     * 执行拦截器链
     * 
     * @param context 消息上下文
     * @return true-所有拦截器都通过，false-被某个拦截器拦截
     */
    public boolean doIntercept(MessageContext context) {
        if (context == null) {
            return false;
        }

        // 如果配置跳过拦截器
        if (context.isSkipInterceptors()) {
            log.debug("消息配置跳过拦截器，直接发送");
            return true;
        }

        for (MessageInterceptor interceptor : interceptors) {
            // 检查是否匹配
            if (!interceptor.matches(context)) {
                continue;
            }

            try {
                // 前置处理
                interceptor.preHandle(context);

                // 执行拦截
                boolean result = interceptor.intercept(context);

                // 后置处理
                interceptor.postHandle(context, result);

                if (!result) {
                    log.warn("消息被拦截器拦截: interceptor={}, context={}", 
                            interceptor.getName(), context);
                    return false;
                }

                log.debug("拦截器通过: interceptor={}", interceptor.getName());

            } catch (Exception ex) {
                log.error("拦截器执行异常: interceptor={}, error={}", 
                        interceptor.getName(), ex.getMessage(), ex);
                
                // 异常处理
                try {
                    interceptor.handleException(context, ex);
                } catch (Exception e) {
                    log.error("拦截器异常处理失败", e);
                }

                // 默认：发生异常则中断
                return false;
            }
        }

        return true;
    }

    /**
     * 获取拦截器数量
     */
    public int size() {
        return interceptors.size();
    }

    /**
     * 获取拦截器列表
     */
    public List<MessageInterceptor> getInterceptors() {
        return new ArrayList<>(interceptors);
    }

    /**
     * 创建构建器
     */
    public static Builder builder() {
        return new Builder();
    }

    /**
     * 构建器
     */
    public static class Builder {
        private final List<MessageInterceptor> interceptors = new ArrayList<>();

        /**
         * 添加拦截器
         */
        public Builder addInterceptor(MessageInterceptor interceptor) {
            if (interceptor != null) {
                this.interceptors.add(interceptor);
            }
            return this;
        }

        /**
         * 批量添加拦截器
         */
        public Builder addInterceptors(List<MessageInterceptor> interceptors) {
            if (interceptors != null) {
                this.interceptors.addAll(interceptors);
            }
            return this;
        }

        /**
         * 构建拦截器链
         */
        public InterceptorChain build() {
            return new InterceptorChain(interceptors);
        }
    }
}

